import 'package:flutter/material.dart';
import 'package:x_custom_widget/image_tool.dart';

import 'custom_container.dart';

class CustomImage extends StatefulWidget {
  final String url;
  final double? size;
  final double? width;
  final double? height;
  final double? radius;
  final BoxFit? fit;

  const CustomImage(
      {Key? key,
      required this.url,
      this.size,
      this.radius,
      this.fit,
      this.width,
      this.height})
      : assert(
            ((width != null || (height != null) && size == null) ||
                (width == null || (height == null) && size != null)),
            '($width 或 $height) 和 $size 不能同时有值,有一个为空'),
        super(key: key);

  @override
  State<CustomImage> createState() => _CustomImageState();
}

class _CustomImageState extends State<CustomImage> {
  Image? image;
  @override
  void initState() {
    super.initState();
  }

  String imageUrl = "";
  @override
  Widget build(BuildContext context) {
    return CustomContainer(
        child: ClipRRect(
      borderRadius: BorderRadius.circular(widget.radius ?? 0),
      child: SizedBox(
          width: widget.width ?? widget.size,
          height: widget.height ?? widget.size,
          child: FutureBuilder(
            future: loadingImage(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                image = snapshot.data as Image;
                return image!;
              } else {
                return Container(color: Colors.grey[200]);
              }
            },
          )),
    ));
  }

  Future<Image> loadingImage() async {
    if (imageUrl != widget.url) {
      imageUrl = widget.url;
      if (widget.url.startsWith("http")) {
        return await netWorkImageWithUrl(
          widget.url,
          fit: widget.fit ?? BoxFit.cover,
        );
      } else {
        return await Future(() => Image.asset(
              imageUrl,
              fit: widget.fit ?? BoxFit.cover,
            ));
      }
    }
    return image!;
  }
}
